﻿namespace PowerSong.Import
    {
    using PowerSong.SongDatabase;
    using System.Collections.Generic;
    using System;

    /// <summary>
    /// A base class that can be extended to provide data import functionality for a new non-PowerSong database type.
    /// </summary>
    public abstract class BaseImport
        {

        /// <summary>
        /// The target database to import items into.
        /// </summary>
        protected Database Destination { get; private set; }

        public delegate void ReportProgressDelegate(int percentage, string status);

        public event ReportProgressDelegate ReportProgress = null;

        public BaseImport(Database destinationDatabase)
            {
            this.Destination = destinationDatabase;
            }

        /// <summary>
        /// Imports data into the target database, returning any error or warning messages that get logged
        /// during the process.
        /// </summary>
        /// <param name="categoryName">The name of a category to assign new songs to when they get imported.</param>
        /// <returns>Warnings or errors raised by the import process.</returns>
        public string[] ImportData(string categoryName)
            {

            // Create a new list to hold all of the resulting messages
            var result = new List<string>();
            try
                {

                // Get or create the default category to import songs into
                Category category = null;
                if (categoryName != null)
                    {
                    category = Destination.Categories.Get(categoryName);
                    if (category == null)
                        {
                        category = new Category(categoryName);
                        Destination.Categories.Write(category);
                        }
                    }

                // Perform the import
                Import(category, result);

                }
            catch (Exception ex)
                {
                result.Add("The import failed for the following reason: " + ex.Message);
                }

            // Return the messages
            return result.ToArray();

            }

        protected void SetProgress(int percentage, string status)
            {
            if (ReportProgress != null) ReportProgress(percentage, status);
            }

        protected abstract void Import(Category category, List<string> messages);

        }

    }
